package com.lance.answer.gui.answer.gk.answer.lms.batch.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.batch.dto.CourseConfig;
import com.lance.answer.gui.answer.gk.answer.lms.batch.dto.LmsWatchDTO;
import com.lance.answer.gui.answer.gk.answer.lms.dto.LmsExamInfo;
import com.lance.answer.gui.answer.gk.answer.lms.export.ExportLmsExamInfo;
import com.lance.answer.gui.answer.gk.answer.lms.util.ImageUtil;
import com.lance.answer.gui.answer.gk.answer.lms.util.LmsUtil;
import com.lance.answer.util.CollectionsUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;


@Slf4j
public class DoAnswerTask extends Thread {


    public static ExecutorService pool = Executors.newSingleThreadExecutor();

    private final String driverPath;
    private final LinkedBlockingDeque<LmsWatchDTO> watchDTOS;

    public DoAnswerTask(String driverPath, LinkedBlockingDeque<LmsWatchDTO> watchDTOS) {
        this.driverPath = driverPath;
        this.watchDTOS = watchDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (watchDTOS.size() > 0) {
            LmsWatchDTO lmsWatchDTO = watchDTOS.take();
            String userName = lmsWatchDTO.getUsername();
            String password = lmsWatchDTO.getPassword();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), watchDTOS.size(), userName, password);
            System.err.println("执行任务11111");
            run(driverPath, lmsWatchDTO);
        }

        if (watchDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    // 完型填空类型
    public static final String CLOZE = "subject ng-scope cloze";

    public static void run(String driverPath, LmsWatchDTO lmsWatchDTO) throws Exception {


        String userName = lmsWatchDTO.getUsername();
        String pwd = lmsWatchDTO.getPassword();
        String teacher = lmsWatchDTO.getTeacher();
        Map<Long, String> courseMap = lmsWatchDTO.getCourseMap();
        // 所有没有做完的课程集合
        Map<Long, String> unDoneCourseMap = Maps.newHashMap();
        Map<String, CourseConfig> courseConfigMap = lmsWatchDTO.getCourseConfigMap();
        for (Long courseId : courseMap.keySet()) {
            String subjectName = courseMap.get(courseId);

            Map<String, AnswerObject> answerMap = lmsWatchDTO.getAnswers().get(courseId);
            if (null == answerMap) {
                continue;
            }
            String completeInfoFilePath = "libs//lmsAnswerInfo//" +teacher+"//"+ subjectName + "//";
            completeInfoFilePath = completeInfoFilePath + userName + "-study.txt";
            File completeInfoFile = new File(completeInfoFilePath);
            if(completeInfoFile.exists()){
                InputStream completeInfoStream = new FileInputStream(completeInfoFile);
                String completeInfoStr = IOUtils.toString(completeInfoStream, "UTF-8");
                List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
                CourseConfig courseConfig = courseConfigMap.get(subjectName);
                if(courseConfig==null|| null == completeInfoList||
                        completeInfoList.isEmpty()||completeInfoList.size()<courseConfig.getQuizSize()){
                    unDoneCourseMap.put(courseId,subjectName);
                }
            }else {
                unDoneCourseMap.put(courseId,subjectName);
            }

        }



        // 说明没有要做的作业了
        if(unDoneCourseMap.size()<1){
            return;
        }

//        System.err.println("unDoneCourseMap?:"+unDoneCourseMap);
//        Thread.sleep(2000000);


        ChromeDriver driver = Util.getDriver(driverPath);
        try {
            String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
            driver.get(url);
            Thread.sleep(3000);



            //  pool.submit(() -> LmsUtil.login(driver, userName, pwd));
            LmsUtil.login(driver, userName, pwd);

            TimeUnit.SECONDS.sleep(10);

            // 要求分数 FIXME 每个课程要求的分数不一样
            int requireScore = 70;

            List<String> filterCourse = lmsWatchDTO.getFilterCourseNames();




            for (Long courseId : unDoneCourseMap.keySet()) {
                String courseName = unDoneCourseMap.get(courseId);
                if (filterCourse.contains(courseName)) {
                    continue;
                }

                Map<String, AnswerObject> answerMap = lmsWatchDTO.getAnswers().get(courseId);

                if (null == answerMap) {
                    log.info("{},{}答案为空", courseId, courseName);
                    continue;
                }

                CourseConfig courseConfig = courseConfigMap.get(courseName);
                if(courseConfig!=null){
                    if(courseConfig.getRequireScore()>0){
                        requireScore = courseConfig.getRequireScore();
                    }
                }
                study(driver, answerMap, courseId, courseName, requireScore, userName, lmsWatchDTO.getTeacher());

            }


        } catch (Exception e) {

        } finally {
            try {
                driver.close();
                driver.quit();
            } catch (Exception e1) {

            }
        }
    }


    private static void study(WebDriver driver, Map<String, AnswerObject> answerMap, Long courseId, String subjectName,
                              int requireScore, String userName,String teacherName) throws Exception {

        // 进入课程首页  FIXME 2022-11-9 注释
//        for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
//            String textContent = we.getText();
//            System.err.println("text:" + textContent);
//            if (textContent.contains(subjectName)) {
//                we.findElement(By.tagName("a")).click();
//                break;
//            }
//        }
        // 进入课程首页  FIXME 2022-11-9 注释
        // https://lms.ouchn.cn/course/29987/ng#/formal-exam

      //  Util.clickLmsCourse(driver,subjectName);
         driver.get("https://lms.ouchn.cn/course/"+courseId+"/ng#/formal-exam");


        Util.switchToLast(driver);


        // TODO 现在开始获取具体课程所有的答题链接：：

        List<LmsExamInfo> lmsExamInfoList = ExportLmsExamInfo.getUserCourseInfo(driver, courseId);

        System.err.println("??????????:" + JSON.toJSONString(lmsExamInfoList));

        List<LmsExamInfo.ExamsDTO> exams = Lists.newLinkedList();
        lmsExamInfoList.forEach(e -> exams.addAll(e.getExams()));

        // ID升序排列
        Collections.sort(exams);

    //    String completeInfoFilePath = "libs//lmsAnswerInfo//" + subjectName + "//";
        String completeInfoFilePath = "libs//lmsAnswerInfo//" +teacherName+"//"+ subjectName + "//";
        File directory = new File(completeInfoFilePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        completeInfoFilePath = completeInfoFilePath + userName + "-study.txt";


        File completeInfoFile = new File(completeInfoFilePath);
        if (!completeInfoFile.exists()) {
            completeInfoFile.createNewFile();
        }
        InputStream completeInfoStream = new FileInputStream(completeInfoFile);
        String completeInfoStr = IOUtils.toString(completeInfoStream, "UTF-8");
        List<CompleteInfo> completeInfoList;
        try {
            completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
            if (null == completeInfoList) {
                completeInfoList = Lists.newArrayList();
            }
        } catch (Exception e) {
            completeInfoList = Lists.newArrayList();
        }


        for (LmsExamInfo.ExamsDTO examsDTO : exams) {
            try {
                String examTitle = examsDTO.getTitle();
                // 排除不计入考核的作业
                if (!Strings.isNullOrEmpty(examTitle) && examTitle.contains("不计入考核")) {
                    continue;
                }


                // 排除已经做了测试的
                String score = examsDTO.getScore();
                // FIXME 分数不一定是整数  比如有87.5
                // FIXME "announce_score_status":"no_announce", 这个字段代表成绩还没有公布，
//                if ("no_announce".equals(examsDTO.getAnnounceAnswerStatus()&&"已提交".equals(examsDTO.get))||
//                        (!Strings.isNullOrEmpty(score) && Double.parseDouble(score) >= requireScore)) {
                if (
                        !Strings.isNullOrEmpty(score) && Double.parseDouble(score) >= requireScore) {
                    //  if (!Strings.isNullOrEmpty(score) && Double.parseDouble(score) >= -1.0) {
                    //    if (!Strings.isNullOrEmpty(score) && Double.parseDouble(score) >= 80) {

                    CompleteInfo completeInfo = new CompleteInfo();
                    completeInfo.setScore(score);
                    completeInfo.setComplete(true);
                    String homeworkUrl = "https://lms.ouchn.cn/course/" + courseId + "/learning-activity#/exam/" + examsDTO.getId();
                    completeInfo.setHomeworkUrl(homeworkUrl);
                    boolean isAdd = true;
                    for (CompleteInfo completeInfo1 : completeInfoList) {
                        if (completeInfo1.getHomeworkUrl().equals(homeworkUrl)) {
                            isAdd = false;
                            break;
                        }
                    }
                    System.err.println("CompleteInfo:" + completeInfo);
                    if (isAdd) {
                        completeInfoList.add(completeInfo);
                    }
                    continue;
                }

//                if(1>0){
//                    continue;
//                }


                // 过滤掉不是形考得 FIXME
                if (!examsDTO.getTitle().contains("形考")
                        && !examsDTO.getTitle().contains("10分")
                        && !examsDTO.getTitle().contains("阶段作业")
                        && !examsDTO.getTitle().contains("考核")
                        && !examsDTO.getTitle().contains("作业")
                        && !examsDTO.getTitle().contains("专题测验")
                        && !examsDTO.getTitle().contains("专题测试")
                        && !examsDTO.getTitle().contains("单元自测")
                        && !examsDTO.getTitle().contains("必选")
                        && !examsDTO.getTitle().contains("阶段性学习测验")
                //        && !examsDTO.getTitle().contains("测试")
                  //      && !examsDTO.getTitle().contains("讲")
                        && !examsDTO.getTitle().contains("平时")
                        && !examsDTO.getTitle().contains("阶段测验")
                        && !examsDTO.getTitle().contains("第一次作业")
                        && !examsDTO.getTitle().contains("第二次作业")
                        && !examsDTO.getTitle().contains("形成性")
                        && !examsDTO.getTitle().contains("综合任务")
                        && !examsDTO.getTitle().contains("过程性测验")
                        && !examsDTO.getTitle().contains("过程性测试")
                        && !examsDTO.getTitle().contains("终结性考试")
                        && !examsDTO.getTitle().contains("终结性考核")
                     //   && !examsDTO.getTitle().contains("测试")
              //          && !examsDTO.getTitle().contains("分")
//                        && !examsDTO.getTitle().contains("终考任务")
//                        && !examsDTO.getTitle().contains("专题检验")
//                        && !examsDTO.getTitle().contains("专题检验")
//                        && !examsDTO.getTitle().contains("法律基础专题")
//                        && !examsDTO.getTitle().contains("宪法知识专题")
//                        && !examsDTO.getTitle().contains("Self-test")
                        && !examsDTO.getTitle().contains("专题检测")
                   //     && !examsDTO.getTitle().contains("单元自测")
//                        && !examsDTO.getTitle().contains("期末综合测试")
//                        && !examsDTO.getTitle().contains("第1次测验")
//                        && !examsDTO.getTitle().contains("第2次测验")
//                        && !examsDTO.getTitle().contains("考试任务二")
//
//                        && !examsDTO.getTitle().contains("学后自测")
//                        && !examsDTO.getTitle().contains("章")
//
//                        && !examsDTO.getTitle().contains("30分") // FIXME
//                        && !examsDTO.getTitle().contains("20分") // FIXME
                ) {
                    continue;
                }
                if(examsDTO.getTitle().contains("不计入")){
                    continue;
                }

                String doExamUrl = "https://lms.ouchn.cn/course/" + courseId + "/learning-activity#/exam/" + examsDTO.getId();
                //      String doExamUrl = "https://lms.ouchn.cn/course/10000000714/learning-activity/full-screen#/exam/10000006125";
                driver.get(doExamUrl);
                try {
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 确认开始答题
                confirmDoAnswer(driver);

                // 找到所有的问题element
                Thread.sleep(5000);
                List<WebElement> webElements = findWeElements(driver, "li[ng-class='subject.type']", 20);
                List<WebElement> questionElements = Lists.newLinkedList();

                webElements.forEach(e -> {
                     if (
                             !e.getAttribute("class").equals("subject ng-scope text")
                             &&!e.getAttribute("class").equals("subject ng-scope matching") //匹配题目 拖拉拽
                     ) {
                        questionElements.add(e);
                    }
                });

                // 开始答题
                doAnswer(driver, questionElements, answerMap);

                // 提交答题并确认提交 button button-green ng-scope
                Thread.sleep(5000);
                try {
                    // right ng-scope 可以判断答题进度来决定是否提交
                    String doneNums = driver.findElement(By.cssSelector("span[ng-bind='progressUi.answeredNum']")).getText();
                    String allNums = driver.findElement(By.cssSelector("span[ng-bind='progressUi.subjectsNum']")).getText();
                    //  if (Integer.parseInt(doneNums) / Integer.parseInt(allNums) < 0.90) {
                    //   if (Integer.parseInt(doneNums) / Integer.parseInt(allNums) < 0.85) {
                    if (Double.parseDouble(doneNums) / Double.parseDouble(allNums) < 0.85 ) {
                      //   Thread.sleep(50000000);
                        System.err.println("完成度不够！！！！！！！！！！");
                        continue;
                    }
                    submitTesting(driver);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Thread.sleep(5000);
            } catch (Exception e) {

            }

        }

            FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");
    }

    public static void confirmDoAnswer(WebDriver driver) throws InterruptedException {

        //  点击开始答题
        driver.findElement(By.cssSelector("div[class='exam-button-container ng-scope']")).findElement(By.tagName("span")).click();
        Thread.sleep(3000);
        //  for = confirm 点击勾选 我已知晓考试要求并承诺遵守考试纪律 ng-valid ng-touched ng-dirty ng-valid-parse ng-empty
        try {
            new WebDriverWait(driver, Duration.ofSeconds(30)).until((ExpectedCondition<WebElement>)
                    d -> Objects.requireNonNull(d).findElement(By.cssSelector("input[name='confirm']"))).click();
        } catch (Exception e) {

        }
        Thread.sleep(3000);

        for (WebElement startAnswerWe : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                d -> Objects.requireNonNull(d).findElements(By.cssSelector("button[class='button button-green medium ng-binding']")))) {
            // button button-green medium ng-binding
            if ("开始答题".equals(startAnswerWe.getText()) || "继续答题".equals(startAnswerWe.getText())) {
                startAnswerWe.click();
                break;
            }

        }
    }


    public static void submitTesting(WebDriver driver) throws Exception {
        // 点击提交  交卷
        driver.findElement(By.cssSelector("a[class='button button-green ng-scope']")).click();

        // button button-green medium
        for (WebElement confirmBtn : findWeElements(driver, "button[class='button button-green medium']", 20)) {
            if ("确定".equals(confirmBtn.getText())) {
                confirmBtn.click();
                break;
            }
        }
    }


    private static void doAnswer(WebDriver driver, List<WebElement> questionWeList, Map<String, AnswerObject> answerMap) throws Exception {

        // fixme
        Thread.sleep(1000);
        // fixme

        System.err.println("questionWeListSize：" + questionWeList.size());


        for (WebElement questionWe : questionWeList) {
            WebElement summaryWe = questionWe.findElement(By.className("summary-title"));

            String questionType = questionWe.getAttribute("class");

            // fixme
            // WebElement titleWe = summaryWe.findElement(By.cssSelector("p[class$='ng-scope']"));
            // 如果是完型填空
            String title = Util.getLmsTitle(summaryWe, true);

            String httpTitle = dealTitleWithHref(title);
            AnswerObject answerObject = answerMap.get(title);
            if (answerObject == null) {
                answerObject = answerMap.get(httpTitle);
            }
            if (answerObject == null) {
                answerObject = answerMap.get(DealJsonString.removeSpace(title));
            }
            if (answerObject == null) {
                answerObject = answerMap.get(DealJsonString.saveZhWord(title));
            }
            if (answerObject == null) {
                System.err.println("答案不存在:" + title);
                // FIXME 如果问题不存在，就用HANLP来匹配
                double similarity = 0.0;
                String answerTitle = "";
                for (Map.Entry<String, AnswerObject> entry : answerMap.entrySet()) {
                    //    double k1 = DealJsonString.getSimilarity(title, entry.getKey());
                    double k1 = DealJsonString.getSimilarity(httpTitle, entry.getKey());
                    if (k1 > similarity) {
                        similarity = k1;
                        answerTitle = entry.getKey();
                    }
                }
                System.err.println("answerTitle:" + answerTitle + " similarity:" + similarity);
                // 相似度为0.9 就选择
                if (similarity > 0.60) {
                    answerObject = answerMap.get(answerTitle);
                } else {
//                    try {
//                        continue;
//                        // Thread.sleep(20000000);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                }
            }
            System.err.println("answerObject:" + JSONObject.toJSONString(answerObject));


            if (null == answerObject) {
                continue;
            }

            switch (answerObject.getQuestionType()) {
                case "1":
                case "2":
                case "3": {
                    // 单选 多选 判断
                    doChoiceExercise(questionWe, answerObject.getAnswers());
                    break;
                }
                case "4": {
                    doGapFilling(questionWe, answerObject.getAnswers());
                    break;
                }
                case "5": {
                    doShortAnswer(questionWe, answerObject.getAnswers());
                    break;
                }
                case "6": {
                    //   doMultiAnswer(driver, questionWe, answerObject.getAnswers());
                    doMultiAnswerByLance2(driver, questionWe, answerObject.getAnswers());
                    break;
                }
                case "8": {
                    doMatching(driver, questionWe, answerObject.getAnswers());
                    break;
                }
                default: {
                    throw new Exception("不支持的题型!" + questionType + answerObject.getQuestionTitle());
                }
            }
        }
    }

    /**
     * 图像 拖拉拽题
     *
     * @param driver
     * @param answerElement
     * @param realAnswers
     */
    private static void doMatching(WebDriver driver, WebElement answerElement, List<String> realAnswers) throws InterruptedException {

        try {
            int index = 0;

            // 所有选项
            List<WebElement> quizWeList = answerElement.findElements(By.cssSelector("div[class='clone-area drag-area ng-scope']"));

            for (WebElement we : answerElement.findElements(By.cssSelector("div[class='list-panel option ng-isolate-scope']"))) {
                String realAnswer = realAnswers.get(index);

                for (WebElement quizWe : quizWeList) {
                    String quizContent = quizWe.findElement(By.cssSelector("div[class='content-center']")).getText();
                    quizContent = Util.dealContent(quizContent);
                    if (!quizContent.equals(realAnswer)) {
                        continue;
                    }
                    new Actions(driver).dragAndDrop(quizWe, we).perform();
                }
                index++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 做完型填空 下拉框|填空题类型的完形填空
     *
     * @param driver
     * @param answerElement
     * @param realAnswers
     */
    private static void doMultiAnswer(WebDriver driver, WebElement answerElement, List<String> realAnswers) throws InterruptedException {

        System.err.println("1111111111111=1111111111111111111111");

        // 填空题类型的完形填空
        List<WebElement> varWeList = Util.findAllByCssSelector(answerElement, "var[context='subject']");
        try {
            if (varWeList != null && varWeList.size() > 0) {
                for (int k = 0; k < varWeList.size(); k++) {
                    WebElement varWe = varWeList.get(k);
                    varWe.clear();
                    varWe.sendKeys(realAnswers.get(k));
                }
                return;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        System.err.println("222222222222=22222222222222222");


        int index = 0;
        List<WebElement> liWeList = answerElement.findElements(By.cssSelector("li[class='sub-subject-content ng-scope']"));
        if (liWeList.size() == 5) {
            for (WebElement liWe : liWeList) {
                for (WebElement labelWe : liWe.findElements(By.tagName("label"))) {
                    WebElement contentWe = Util.findByCssSelector(labelWe, "div[class='option-content']");
                    if (contentWe == null) {
                        continue;
                    }
                    if (realAnswers.get(index).equals(contentWe.getText())) {
                        System.err.println("contentWe.getText()):" + contentWe.getText());
                        labelWe.click();
                        break;
                    }
                }
                index++;
            }
            return;
        }

        System.err.println("3333333333333==3333333333333");


        driver.manage().window().maximize();
        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,10000)");

        Thread.sleep(5000);

        try {


            List<WebElement> ngWeList = Lists.newArrayList();

            for (WebElement ngWe : answerElement.findElements(By.cssSelector("*[class='ng-scope']"))) {
                if (ngWe.getTagName().equals("div")) {
                    continue;
                }
                WebElement selectWe = Util.findByTagName(ngWe, "select");
                if (selectWe != null) {
                    System.err.println("????ngWeeeeeeeeeeeeee" + ngWe.getText());
                    ngWeList.add(ngWe);
                }
            }


            // 找到5个选项框 ui-multiselect ui-widget ui-state-default ui-corner-all multi-select gray
            // 先点击button ，然后再找选项
            List<WebElement> buttonWeList = Lists.newArrayList();

            for (WebElement ngWe : ngWeList) {
                buttonWeList.addAll(ngWe.findElements(By.cssSelector("button[class^='ui-multiselect ui-widget']")));
            }


            System.err.println("buttonWeListSize:" + buttonWeList.size());


            for (; index < buttonWeList.size(); index++) {
                buttonWeList.get(index).click();

                Thread.sleep(2000);

                WebElement divWe = answerElement.findElements(By.cssSelector("div[class^='ui-multiselect-menu ui-widget ui-widget-content ui-corner-all ui-multiselect-single multi-select']")).get(index);
                for (WebElement labelWe : divWe.findElements(By.tagName("label"))) {
                    System.err.println("labelWe::" + labelWe.findElement(By.tagName("span")).getText());
                    if (realAnswers.get(index).equals(labelWe.getText())) {
                        labelWe.click();
                        break;
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 做完型填空 下拉框|填空题类型的完形填空
     *
     * @param driver
     * @param answerElement
     * @param realAnswers
     */
    private static void doMultiAnswerByLance(WebDriver driver, WebElement answerElement, List<String> realAnswers) throws InterruptedException {

        System.err.println("1111111111111=1111111111111111111111");

        // 填空题类型的完形填空
        List<WebElement> varWeList = Util.findAllByCssSelector(answerElement, "var[context='subject']");
        try {
            if (varWeList != null && varWeList.size() > 0) {
                for (int k = 0; k < varWeList.size(); k++) {
                    WebElement varWe = varWeList.get(k);
                    varWe.clear();
                    varWe.sendKeys(realAnswers.get(k));
                }
                return;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        System.err.println("222222222222=22222222222222222");


        Thread.sleep(5000);


        // 找到5个选项框 select
        List<WebElement> selectElement = Util.findAllByCssSelector(answerElement, "select[class='___select-answer']");
        if (CollectionsUtil.isEmpty(selectElement)) {
            return;
        }
        Thread.sleep(2000);
        int index = 0;
        for (WebElement element : selectElement) {
            Select select = (Select) element;
            int j = 0;
            //先打印看看
            System.out.println("先打印看看");
            for (WebElement option : select.getOptions()) {
                System.out.println(option.getText());
            }

            //挑选答案
            for (WebElement option : select.getOptions()) {
                if (realAnswers.get(index).equalsIgnoreCase(option.getText())) {
                    select.selectByIndex(j);
                    break;
                }
                j++;
            }
            index++;
        }
    }


    /**
     * 做完型填空 下拉框|填空题类型的完形填空
     *
     * @param driver
     * @param answerElement
     * @param realAnswers
     */
    private static void doMultiAnswerByLance2(WebDriver driver, WebElement answerElement, List<String> realAnswers) throws InterruptedException {


        System.err.println("===============doMultiAnswerByLance2===========");

        int index = 0;
        try{
            List<WebElement> liWeList = answerElement.findElements(By.cssSelector("li[class='sub-subject-content ng-scope']"));
            System.err.println("size================"+liWeList.size());

            for(WebElement liWe:liWeList){
                WebElement olWe = liWe.findElement(By.cssSelector("ol[class='subject-options']"));
                for(WebElement liSectionWe:olWe.findElements(By.cssSelector("li[class='option ng-scope vertical']"))){

                    String content = liSectionWe.findElement(By.cssSelector("div[class='option-content']")).getText();
                    if (realAnswers.get(index).trim().equalsIgnoreCase(content)) {
                        liSectionWe.findElement(By.tagName("label")).click();
                        break;
                    }
                }
                index++;
            }
        }catch (Exception e){

        }

        try {
          // ?????11-9 todo 需要测试  List<WebElement> buttonWeList = driver.findElements(By.cssSelector("button[class^='ui-multiselect ui-widget ui-state-default']"));
            List<WebElement> buttonWeList = answerElement.findElements(By.cssSelector("button[class^='ui-multiselect ui-widget ui-state-default']"));


            for (WebElement buttonWe : buttonWeList) {

                //  buttonWe.findElement(By.cssSelector("span[class='ui-multiselect-open']")).click();
                buttonWe.findElements(By.tagName("span")).get(1).click();

                Thread.sleep(2000);

                WebElement divWe = answerElement.findElements(By.cssSelector("div[class^='ui-multiselect-menu ui-widget ui-widget-content ui-corner-all ui-multiselect-single multi-select']")).get(index);
                for (WebElement labelWe : divWe.findElements(By.tagName("label"))) {
                    System.err.println("labelWe::" + labelWe.findElement(By.tagName("span")).getText());
                    if (realAnswers.get(index).trim().equalsIgnoreCase(labelWe.getText().trim())) {
                        labelWe.click();
                        break;
                    }
                }

                index++;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        System.err.println("===============doMultiAnswerByLance2===========");


    }


    /**
     * 做完型填空 下拉框|填空题类型的完形填空
     *
     * @param driver
     * @param answerElement
     * @param realAnswers
     */
    private static void doMultiAnswer22222(WebDriver driver, WebElement answerElement, List<String> realAnswers) throws InterruptedException {

        int index = 0;
        List<WebElement> liWeList = answerElement.findElements(By.cssSelector("li[class='sub-subject-content ng-scope']"));
        if (liWeList.size() == 5) {

            for (WebElement liWe : liWeList) {
                for (WebElement labelWe : liWe.findElements(By.tagName("label"))) {
                    WebElement contentWe = Util.findByCssSelector(labelWe, "div[class='option-content']");
                    if (contentWe == null) {
                        continue;
                    }
                    if (realAnswers.get(index).equals(contentWe.getText())) {
                        labelWe.click();
                        break;
                    }
                }
                index++;
            }
            return;
        }


        driver.manage().window().maximize();
        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,10000)");

        Thread.sleep(5000);

        try {

            int count = 0;
            WebElement olWe = null;
            for (WebElement ngWe : answerElement.findElements(By.cssSelector("*[class='ng-scope']"))) {
                if (ngWe.getTagName().equals("div")) {
                    continue;
                }
                WebElement selectWe = Util.findByTagName(ngWe, "select");
                if (selectWe != null) {
                    System.err.println("????ngWeeeeeeeeeeeeee" + ngWe.getText());
                    count++;
                    olWe = ngWe;
                }
            }
            System.err.println("count:" + count);

            // 如果count=1 ，说明所有的选择标签都在一个ol标签下面
            // FIXME 2022-0508 ???????? 如果count=2，说明所有的选择标签都在一个ol标签下面
            if (count == 1) {

                for (WebElement ngWe : olWe.findElements(By.tagName("li"))) {

                    System.err.println("ngWe:" + ngWe.getText());

                    WebElement selectWe = Util.findByTagName(ngWe, "select");
                    if (selectWe == null) {
                        continue;
                    }

                    Thread.sleep(2000);
                    //    WebElement span =  ngWe.findElement(By.cssSelector("span[class='ui-multiselect-open']"));
                    WebElement span = ngWe.findElement(By.cssSelector("button[class^='ui-multiselect ui-widget']"));
                    Thread.sleep(2000);
                    span.click();

                    Thread.sleep(2000);

                    WebElement divWe = answerElement.findElements(By.cssSelector("div[class^='ui-multiselect-menu ui-widget ui-widget-content ui-corner-all ui-multiselect-single multi-select']")).get(index);
                    //    new Actions(driver).contextClick(divWe).perform();;
                    //   divWe.click();
                    for (WebElement labelWe : divWe.findElements(By.tagName("label"))) {
                        System.err.println("labelWe::" + labelWe.findElement(By.tagName("span")).getText());
                        if (realAnswers.get(index).equals(labelWe.getText())) {
                            labelWe.click();
                            break;
                        }
                    }

                    index++;

                }
            }

            if (count == 5) {
                for (WebElement ngWe : answerElement.findElements(By.cssSelector("*[class='ng-scope']"))) {

                    if (ngWe.getTagName().equals("div")) {
                        continue;
                    }
                    System.err.println("ngWe:" + ngWe.getText());

                    WebElement selectWe = Util.findByTagName(ngWe, "select");
                    if (selectWe == null) {
                        continue;
                    }

                    Thread.sleep(2000);
                    //    WebElement span =  ngWe.findElement(By.cssSelector("span[class='ui-multiselect-open']"));
                    WebElement span = ngWe.findElement(By.cssSelector("button[class^='ui-multiselect ui-widget']"));
                    Thread.sleep(2000);
                    span.click();

                    Thread.sleep(2000);

                    WebElement divWe = answerElement.findElements(By.cssSelector("div[class^='ui-multiselect-menu ui-widget ui-widget-content ui-corner-all ui-multiselect-single multi-select']")).get(index);
                    //    new Actions(driver).contextClick(divWe).perform();;
                    //   divWe.click();
                    for (WebElement labelWe : divWe.findElements(By.tagName("label"))) {
                        System.err.println("labelWe::" + labelWe.findElement(By.tagName("span")).getText());
                        if (realAnswers.get(index).equals(labelWe.getText())) {
                            labelWe.click();
                            break;
                        }
                    }

                    index++;

                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private static void doShortAnswer(WebElement answerElement, List<String> realAnswers) throws UnsupportedEncodingException {

        //   answerElement.findElement(By.cssSelector("div[class='subject-body short-answer']")).sendKeys(realAnswers.get(0)); 不行
        answerElement.findElement(By.cssSelector("div[class='simditor-body needsclick']")).clear();
        answerElement.findElement(By.cssSelector("div[class='simditor-body needsclick']")).sendKeys(realAnswers.get(0));

    }

    private static void doGapFilling(WebElement answerElement, List<String> realAnswers) {

        // 填空题类型的完形填空
        List<WebElement> varWeList = Util.findAllByCssSelector(answerElement, "var[context='subject']");
        try {
            if (varWeList != null) {
                for (int k = 0; k < varWeList.size(); k++) {
                    WebElement varWe = varWeList.get(k);
                    varWe.clear();
                    varWe.sendKeys(realAnswers.get(k));
                }
                return;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
//
//        try {
//            StringBuilder sb = new StringBuilder();
//            realAnswers.forEach(e -> sb.append(e).append(" "));
//            answerElement.findElement(By.cssSelector("var[context='subject']")).clear();
//            answerElement.findElement(By.cssSelector("var[context='subject']")).sendKeys(sb.toString());
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


    private static void doChoiceExercise(WebElement answerElement, List<String> realAnswers) {
        // 遍历题目的每一个选项
        for (WebElement singleAnswerElement : answerElement.findElements(By.cssSelector("li[class='option ng-scope vertical']"))) {

            WebElement answerWe = singleAnswerElement.findElement(By.cssSelector("div[class='option-content']"));
//            String answerContent = answerWe.getText();
//            //兼容特殊字符
//            answerContent = Util.dealContent(answerContent);
//            answerContent = DealJsonString.saveZhWord(answerContent);
//            System.err.println("answerContent:" + answerContent);
            String answerContent = Util.getLmsTitle(answerWe, false);
            // 找到单选框或复选框
            // el-checkbox el-radio
            //     WebElement labelElement = singleAnswerElement.findElement(By.cssSelector("label[ng-class='{'answered-option': option.id == subject.answeredOption}']"));
            WebElement labelElement = singleAnswerElement.findElement(By.tagName("label"));

            // 找到真正的点击按钮 el-radio__input el-checkbox__input
            WebElement realClickElement = singleAnswerElement.findElement(By.cssSelector("span[class='left']"));

            String labelClass = labelElement.getAttribute("class");
            System.err.println("labelClass:" + labelClass);

            WebElement clickWebElement = labelElement.findElement(By.tagName("input"));
            // FIXME 判断题0：对 1：错
            // 这里的ID是每个选项的ID answerContent是每个选项的内容
            for (String realAnswer : realAnswers) {
                realAnswer = Util.dealContent(realAnswer);
                System.err.println("origin:" + answerContent);
                // if (answerContent.equals(realAnswer)) {
                  if (DealJsonString.delHTMLTag(answerContent).equalsIgnoreCase(DealJsonString.delHTMLTag(realAnswer))) {
             //   if (!Strings.isNullOrEmpty(answerContent) && answerContent.equals(realAnswer)) {
                    //   System.err.println("realAnswer:" + realAnswer);
                    assert clickWebElement != null;
                    if (!clickWebElement.isSelected()) {
                        //   realClickElement.click();
                        clickWebElement.click();
                    }
                }
                if (realAnswer.contains("http")) {
                    try {
                        System.err.println("realAnswer::::" + dealTitleWithHref(realAnswer));
                        System.err.println("singleAnswerElement::::" + dealTitleWithHref(Util.getAnswer(answerWe)));
                        if (dealTitleWithHref(realAnswer).equals(dealTitleWithHref(Util.getAnswer(answerWe)))) {
                            if (!clickWebElement.isSelected()) {
                                clickWebElement.click();
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }


        }
    }


// 明天处理一下标题

    // 处理带图片的答案；// 只剩下图片
    public static String dealTitleWithHref(String answerOrTitle) {
        if (!answerOrTitle.contains("http")) {
            return answerOrTitle;
        }
        String realAnswerCode = answerOrTitle.substring(0, answerOrTitle.indexOf("|[") + 2);
        answerOrTitle = answerOrTitle.substring(answerOrTitle.indexOf("|[") + 2, answerOrTitle.length() - 1);
        System.err.println("realAnswer2222:" + answerOrTitle);
        if (answerOrTitle.contains(",")) {
            for (String href : answerOrTitle.split(",")) {
                realAnswerCode += JSON.toJSONString(ImageUtil.getImageFromNetByUrl(href));
            }
        } else {
            realAnswerCode += JSON.toJSONString(ImageUtil.getImageFromNetByUrl(answerOrTitle));
        }
        return realAnswerCode;
    }


    public static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }


}
